package com.piece.core.log.service;

import com.alibaba.fastjson.JSON;
import com.piece.core.log.client.BeanPostLogService;
import com.piece.core.log.client.dto.BeanPostLogDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 审计日志实现类
 */
@Slf4j
@Component("bean_post_log_service_logger")
@ConditionalOnProperty(name = "spring.log.type", havingValue = "logger")
public class BeanPostLogServiceLogger implements BeanPostLogService {

    /**
     * 日志格式：{时间}|{应用名}|{数据源}|{方法}|{数据表}|{详情}|{租户id}|{操作用户id}|{操作用户名}|{访问ip}|{操作城市}|{操作地点}|{错误消息}
     */
    private static final String MSG_PATTERN = "{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}";

    @Async
    @Override
    public BeanPostLogDTO save(BeanPostLogDTO beanPostLog) {
        log.info(MSG_PATTERN
                , "请求时间=" + LocalDateTime.ofInstant(beanPostLog.getOperaTime().toInstant(), ZoneId.of("UTC")).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))
                , "应用名=" + beanPostLog.getApplicationName()
                , "数据源=" + beanPostLog.getSource()
                , "方法=" + beanPostLog.getType()
                , "数据表=" + beanPostLog.getTableName()
                , "详情=" + JSON.toJSONString(beanPostLog.getDesc())
                , "租户ID=" + beanPostLog.getClientId()
                , "操作用户ID=" + beanPostLog.getOperaId()
                , "操作用户名=" + beanPostLog.getOperaName()
                , "访问ip=" + beanPostLog.getIp()
                , "操作城市=" + beanPostLog.getCity()
                , "操作地点=" + beanPostLog.getArea()
                , "错误消息=" + (beanPostLog.getStatus().equals("1") ? beanPostLog.getDesc() : ""));

        return beanPostLog;
    }

    @Override
    public void delete(String id) {
    }

    @Override
    public List<BeanPostLogDTO> findByCondition(Map<String, Object> param) {
        return Collections.emptyList();
    }
}
